package com.github.bobjoy.java.rpc.provider;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;
import java.net.Socket;

public class RpcImporter<S> {

    @SuppressWarnings("unchecked")
    public S importer(Class<?> serviceClass, InetSocketAddress address) {
        return (S) Proxy.newProxyInstance(serviceClass.getClassLoader(),
                new Class<?>[]{serviceClass.getInterfaces()[0]}, (proxy, method, args) -> {

                    Socket socket = null;
                    ObjectOutputStream output = null;
                    ObjectInputStream input = null;

                    try {

                        socket = new Socket();
                        socket.connect(address);

                        output = new ObjectOutputStream(socket.getOutputStream());
                        output.writeUTF(serviceClass.getName());
                        output.writeUTF(method.getName());
                        output.writeObject(method.getParameterTypes());
                        output.writeObject(args);

                        input = new ObjectInputStream(socket.getInputStream());
                        return input.readObject();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (input != null) {
                                input.close();
                            }
                            if (output != null) {
                                output.close();
                            }
                            if (socket != null) {
                                socket.close();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }


                    return null;
                });
    }

}
